package com.sxf.controller.interceptor;

import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.cache.CacheManager;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.sxf.common.tools.WPConstants;
import com.sxf.domain.viewbean.UserVO;
import com.sxf.util.CookieUtils;

/**
 * @author phsxf01
 * 
 */
@Deprecated
public class LoginInterceptor extends HandlerInterceptorAdapter {
	// @Resource(name = "memcachedClient")
	// private MemcachedClient memcachedClient;
	@Resource(name = "memCacheManager")
	private CacheManager cm;

	// 生成视图之前执行(Action):
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		return super.preHandle(request, response, handler);
	}

	// 生成视图之前执行(controller方法执行后执行)
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler, ModelAndView mav)
			throws Exception {
		saveUser(request, response, mav);
		super.postHandle(request, response, handler, mav);
	}

	// 最后执行，可用于释放资源
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * 保存用户信息
	 * 
	 * @param mav
	 * @param nr
	 */
	private void saveUser(HttpServletRequest request,
			HttpServletResponse response, ModelAndView mav) {
		Object obj = mav.getModel().get(WPConstants.LOGIN_USER);
		if (obj != null && obj instanceof UserVO) {
			UserVO user = (UserVO) obj;
			String uuid = UUID.randomUUID().toString().replaceAll("[-]", "");
			cm.getCache(WPConstants.SESSION_CACHE).put(uuid, user);
			CookieUtils.addCookie(request, response, CookieUtils.USER_ID, uuid);
		}
	}

}
